<?php

namespace App\Services;

use App\Models\AdminUser;
use App\Models\Project;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class WebsocketDataService
{
    /**
     * @throws Exception
     */
    public function __construct()
    {

    }

    public function webConfig()
    {
        $config = [
            'title' => '一颗优雅草科技有限公司',
            'datetime' => date('Y年m月d日', time()) . ' 星期' . date('w', time()),
        ];
        return $config;
    }

    /**
     * 项目月度走势图
     *
     * @param Request $request
     * @return array|string|string[]
     */
    public function getProjectMCount()
    {
        //按月获取每月项目总数量，没有项目的月份就默认返回0
        $project_m_count = array();
        for ($i = 1; $i <= 12; $i++) {
            $num = \App\Models\Project::whereMonth('created_at', $i)->count() ?? 0;
            $project_m_count[] = $num;

        }
        $project_m_count = json_encode($project_m_count);
        //将json数据转换成[10, 8, 36, 12, 24, 16, 48, 32, 18, 14, 66, 70]，不需要下标
        $project_m_count = str_replace('"', '', $project_m_count);
        $project_m_count = str_replace('{', '[', $project_m_count);
        $project_m_count = str_replace('}', ']', $project_m_count);
//        dd($project_m_count);
        return $project_m_count;
    }

    /**
     * 最新项目30个
     */
    public function getProjectProgress()
    {
        $project_progress = [];
        $projects = \App\Models\Project::query()
            ->orderBy('created_at', 'desc')
            ->limit(30)
            ->get();

        foreach ($projects as $project) {
            $project_progress[] = [
                'name' => $project->name,
                'schedule' => (string)($project->created_at),
            ];
        }

        return $project_progress;
    }


    /**
     * 销冠排行
     *
     */
    public function getProjectTop()
    {
        $admin = new AdminUser();
//        $salespersons = $admin->alluser('salesperson');
        $salespersons = AdminUser::query()->get();
        //统计指定用户模型在项目中的金额，并按金额排行
        $salesperson = $salespersons->filter(function ($item, $key) {
//            $item->money = (int) \App\Models\Project::where('user_id', $item->id)->where('status', '>', 2)->sum('amount');
            $item->money = \App\Models\Project::where('user_id', $item->id)->sum('amount');
            $item->avatar = 'uploads/' . $item->avatar ?? 'qiaoba.jpg';
            return $item->money > 0;
        });
        $new_salesperson = $salesperson->map(function ($item) {
            unset($item['password']);
            unset($item['remember_token']);
            unset($item['created_at']);
            unset($item['updated_at']);
            unset($item['department_id']);
            unset($item['username']);
            return $item;
        });
// 按money大小排序
        $new_salesperson = $new_salesperson->sortByDesc('money');
        $new_arr = $new_salesperson->values()->all();
        foreach ($new_arr as $key => &$value) {
            $value = $value->toArray();
        }
        return $new_arr;
    }

    /**
     * 统计数据
     */
    public function getStatistics()
    {
        // 获取所有项目数据
        $projects = cache()->remember('all_projects', now()->addMinutes(1), function () {
            // 如果缓存不存在，执行查询并返回结果
            return \App\Models\Project::all()->toArray();
        });

// 初始化统计数组
        $statistics = [
            'project_count' => 0,
            'project_money' => 0,
            'project_ok_money' => 0,
            'project_ok_count' => 0,
            'project_cost' => 0,
            'project_money_month' => 0,
            'project_ok_money_month' => 0,
            'project_ok_count_month' => 0,
            'project_cost_month' => 0,
            'project_count_month' => 0,
        ];

// 遍历项目数组进行统计
        foreach ($projects as $project) {
            // 项目总数累加
            $statistics['project_count']++;
            // 项目总预算累加
            $statistics['project_money'] += $project['budget'];
            // 项目成本累加
            $statistics['project_cost'] += $project['project_cost'];
            $projectCreatedAt = Carbon::parse($project['created_at']);
            // 获取当前月份的第一天和最后一天
            $firstDayOfMonth = Carbon::now()->startOfMonth();
            $lastDayOfMonth = Carbon::now()->endOfMonth();

            // 使用Carbon的isBetween方法判断created_at是否在当月范围内
            $isInCurrentMonth = $projectCreatedAt->between($firstDayOfMonth, $lastDayOfMonth, true, true);
            // 如果项目状态为5，则累加完成的金额和项目数量
            if ($project['status'] == 5) {
                $statistics['project_ok_money'] += $project['amount'] ?? 0;
                $statistics['project_ok_count']++;
                if ($isInCurrentMonth) {
                    $statistics['project_ok_money_month'] += $project['amount'] ?? 0;
                    $statistics['project_ok_count_month']++;
                }
            }

            if ($isInCurrentMonth) {
                $statistics['project_money_month'] += $project['budget'];
                $statistics['project_cost_month'] += $project['project_cost'];
                $statistics['project_count_month']++;
            }
        }
        // 格式化金额
        $statistics['project_money'] = $statistics['project_money'] / 10000;
        $statistics['project_ok_money'] = (int)$statistics['project_ok_money'] / 10000;
        $statistics['project_money_month'] = (int)$statistics['project_money_month'] / 10000;
        $statistics['project_ok_money_month'] = (int)$statistics['project_ok_money_month'] / 10000;
        $statistics['project_cost'] = (int)$statistics['project_cost'] / 10000;
        $statistics['project_cost_month'] = $statistics['project_cost_month'] / 10000;
//        dd($statistics);
        return $statistics;
    }

    /**
     * 按客户地区统计项目金额
     */
    public function getStatisticsByRegion()
    {

        $rankings = Project::select('customer_id')
            ->selectRaw('SUM(amount) as total_amount')
            ->selectRaw('COUNT(*) as total_count')
            ->with('customer')
            ->groupBy('customer_id')
            ->orderByDesc('total_amount')
            ->get()->toArray();
        $rankingss = array_map(function ($item) {
            return [
                'name' => $item['customer']['province_name_ch'],
                'value' => $item['total_amount'] / 100,
                'count' => $item['total_count'],
            ];
        }, $rankings);
        $rankingsp['data'] = $rankingss;
        $rankingsp['total_amount'] = array_sum(array_column($rankings, 'total_amount')) / 100;
        return $rankingsp;
    }


}
